<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 平衡二叉树：左右子节点的高度差<=1
            思路：遍历每一个节点，判断其左右子节点的高度差是否小于等于1
            因此没必要层序遍历，只需要先序遍历即可
            */
            var isBalanced = function (root) {
                if (!root) return true
                let flag = true
                function preOrder(root) {
                    if (!root) return
                    //先序遍历
                    let leftDepth = getDepth(root.left)
                    let rightDepth = getDepth(root.right)
                    if (Math.abs(leftDepth - rightDepth) > 1) flag = false
                    preOrder(root.left)
                    preOrder(root.right)
                }
                preOrder(root)
                return flag

                function getDepth(root) {
                    if (!root) return 0
                    return Math.max(getDepth(root.left), getDepth(root.right)) + 1
                }
            }
        </script>
    </body>
</html>
